// const { query } = require('express');
var express = require('express');
var router = express.Router();
const mysql = require('../utils/mysql.js');
const jiami = require('../utils/jiami');
const jwt = require('jsonwebtoken');

const secretKey = '666'
const { expressjwt } = require('express-jwt');

const upload = require('../utils/upload');
const { json } = require('express');


/**
 * @apiDefine CODE_200
 * @apiSuccess (Reponse 200) {Number} code 0 为成功，-1位异常
 * @apiSuccess (Reponse 200) {Json/Array/Null} data 数组或null，需要根据情况判断，一般有值时为数据类型，没有值时为[]或null
 * @apiSuccess (Reponse 200) {String} msg 请求成功/失败描述信息
 * @apiSuccess (Reponse 200) {String} [error_code] 错误码，有时没有
 * @apiSuccessExample {json} Response 200 Example
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 0,
 *      "data": [],
 *      "msg": "操作成功"
 *    }
 */


router.ws('/mySocketUrl', (ws, req) => {
    // console.log('连接成功', ws)

    ws.send('来自服务端推送的消息')

    ws.on('message', function (msg) {
        ws.send(`收到客户端的消息为：${msg}，再返回去`)
    })

    // 使用定时器不停的向客户端推动消息
    let timer = setInterval(() => {
        ws.send(`服务端定时推送消息: ${getNowTime()}`)
    }, 1000)

    ws.on('close', function (e) {
        // console.log('连接关闭')
        clearInterval(timer)
        timer = null
    })
})

//用户登录************************************************************************************************* 
router.post('/userlogin', async function (req, res) {
    const { uid, pwd } = req.body;
    const result = await mysql('select * from users where username=? and password=?', [uid, pwd]);
    console.log(result);
    if (result.length > 0) {

        res.json({
            code: 200,
            message: '登录成功',

            token: jwt.sign({ username: uid, id: result[0].id }, secretKey, { expiresIn: 60 * 60 * 24 })

        })
    } else {
        res.json({
            code: 400,
            message: '用户名密码不正确'
        })
    }
})

//用户注册************************************************************************************************* 
router.post('/userreg', async function (req, res, next) {
    const { uid, pwd, auth } = req.body;
    console.log(req.body)
    //验证数据是否重复
    const [{ count }] = await mysql('select count(*) as count from users where username = ?', [uid]);
    if (count > 0) {
        res.json({
            code: 400,
            message: '用户名已存在'
        })
    } else {
        await mysql('insert into users (username,password,auth,createdAt,updatedAt) values (?,?,?,?,?)',
            [uid, pwd, auth, new Date(), new Date()]
        );
        res.json({
            code: 200,
            message: '注册成功'
        })
    }

});

// token验证*********************************************************************************************************************
router.all('*', expressjwt({
    secret: secretKey,//密钥
    algorithms: ['HS256'] // t的加密算法
}))
/**
 * 查询所有服务类商品评论
 * @api {post} api/getAllComment 获取所有服务类商品评论
 * @apiName getAllComment
 * @apiDescription 获取所有服务类商品评论
 * @apiGroup api
 * @apiVersion 1.0.0
 * @apiParam {number} pageSize 每页显示数
 * @apiParam {number} currentPage 当前页
 * @apiParamExample  {type} Request-Example:
 *    {
 *      "pageSize": 6,
 *      "currentPage": 1
 *    }
 * @apiSuccessExample {type} Success-Response
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 0,
 *      "data": [],
 *      "total":6,
 *      "msg": "true"
 *    }
 * @apiSampleRequest http://localhost:3000/api/getAllComment
 * @apiUse CODE_200
 */
//查询所有服务评论*************************************************************************************************
router.post('/getAllComment', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM servecomment  ORDER BY createdAt DESC LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM servecomment '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//根据服务id查询服务评论*************************************************************************************************
router.post('/getCommentBycmdId', async function (req, res) {
    let { pageSize, currentPage, commodityid } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM servecomment WHERE commodityid=? ORDER BY createdAt DESC LIMIT ?,?',
        [commodityid, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM servecomment WHERE commodityid=?', [commodityid]
    )
    console.log(data);
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//增加服务评论*************************************************************************************************
router.post('/addComment', async function (req, res) {
    const userid = req.auth.id
    const { score, content, commodityid } = req.body;
    await mysql(' insert into servecomment (userid,score,content,commodityid,updatedAt) values (?,?,?,?,now())',
        [userid, score, content, commodityid]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//删除服务评论*************************************************************************************************
router.delete('/deleteComment', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM servecomment WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//查询所有商品评论*************************************************************************************************
router.post('/getAllGoodcomment', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM goodcomment ORDER BY createdAt DESC LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM goodcomment '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//根据商品id查询商品评论*************************************************************************************************
router.post('/getGoodcommentByorderId', async function (req, res) {
    let { pageSize, currentPage, orderid } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM goodcomment WHERE orderid=? ORDER BY createdAt DESC LIMIT ?,?',
        [orderid, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM goodcomment WHERE orderid=?', [orderid]
    )
    console.log(data);
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//增加商品评论*************************************************************************************************
router.post('/addGoodcomment', async function (req, res) {
    const userid = req.auth.id
    const { score, content, orderid } = req.body;
    await mysql(' insert into goodcomment (userid,score,content,orderid,updatedAt) values (?,?,?,?,now())',
        [userid, score, content, orderid]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//删除商品评论*************************************************************************************************
router.delete('/deleteGoodcomment', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM goodcomment WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//查询所有帖子*************************************************************************************************
router.post('/getAllShare', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM share  ORDER BY updatedAt DESC LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM share '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//增加帖子*************************************************************************************************
router.post('/addShare', async function (req, res) {
    const { title, vedio, detail, serveid, hot, fav, classid } = req.body;
    await mysql(' insert into share (title,vedio,detail,serveid,hot,fav,class,createdAt,updatedAt) values (?,?,?,?,?,?,?,now(),now())',
        [title, vedio, detail, serveid, hot, fav, classid]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//删除帖子*************************************************************************************************
router.delete('/deleteShare', async function (req, res) {
    const { shareid } = req.query
    await mysql('DELETE FROM share WHERE id=? ', [Number(shareid)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//修改帖子*************************************************************************************************
router.put("/updateShare", async function (req, res) {
    const { shareid, title, vedio, detail, serveid, hot, fav, classid } = req.body
    let cmd_filed = [];
    let cmd_arr = [];
    if (title) {
        cmd_filed.push("title=?")
        cmd_arr.push(title)
    }
    if (vedio) {
        cmd_filed.push("vedio=?")
        cmd_arr.push(vedio)
    }
    if (detail) {
        cmd_filed.push("detail=?")
        cmd_arr.push(detail)
    }
    if (hot) {
        cmd_filed.push("hot=?")
        cmd_arr.push(hot)
    }
    if (fav) {
        cmd_filed.push("fav=?")
        cmd_arr.push(fav)
    }
    if (serveid) {
        cmd_filed.push("serveid=?")
        cmd_arr.push(serveid)
    }
    if (classid) {
        cmd_filed.push("class=?")
        cmd_arr.push(classid)
    }
    cmd_arr.push(Number(shareid))
    let sql = '';
    sql = " UPDATE share SET ";
    sql += cmd_filed.join(",");
    sql += " ,updatedAt = now() where id = ? "

    const usersql = await mysql(sql, cmd_arr)

    console.log(usersql);
    res.json({
        code: 200,
        flag: true,
        msg: '修改成功'
    })
})
//增加帖子热度*************************************************************************************************
router.post('/raiseSharehot', async function (req, res) {
    let { shareid } = req.body;
    const data = await mysql(
        'SELECT * FROM servecomment WHERE id=? ',
        [shareid]
    )
    await mysql("update goods set hot = ? where id = ? ", [Number(data[0].hot) + 10, shareid])

    console.log(data);
    res.json({
        flag: true,
        code: 200,
        data,
    })
})

//查询所有分类管理*************************************************************************************************
router.get('/getAllServeclass', async function (req, res) {

    const data = await mysql(
        'SELECT * FROM serveclass  ORDER BY classid  '
    )
    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM serveclass '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//增加分类管理*************************************************************************************************
router.post('/addServeclass', async function (req, res) {
    const { name, isfather } = req.body;
    await mysql(` insert into serveclass (name, isfather,state) values (?,?,1)`,
        [name, isfather]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//修改分类管理(包括状态)*************************************************************************************************
router.put("/updateServeclass", async function (req, res) {
    const { classid, name, isfather, state } = req.body
    let cmd_filed = [];
    let cmd_arr = [];

    if (name) {
        cmd_filed.push("name=?")
        cmd_arr.push(name)
    }
    if (isfather) {
        cmd_filed.push("isfather=?")
        cmd_arr.push(isfather)
    }
    if (state) {
        cmd_filed.push("state=?")
        cmd_arr.push(state)
    }
    cmd_arr.push(Number(classid))
    let sql = '';
    sql = " UPDATE serveclass SET ";
    sql += cmd_filed.join(",");
    sql += " where classid = ? "

    const usersql = await mysql(sql, cmd_arr)

    console.log(usersql);
    res.json({
        code: 200,
        flag: true,
        msg: '修改成功'
    })
})
//查询所有用户收货地址*************************************************************************************************
router.post('/getAllLocation', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM location LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM location '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//查询用户收货地址(根据用户id查)*************************************************************************************************
router.post('/getAllLocationByid', async function (req, res) {
    const userid = req.auth.id
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM location where userid = ? LIMIT ?,?',
        [userid, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM location '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//增加用户收货地址*************************************************************************************************
router.post('/addLocation', async function (req, res) {
    const userid = req.auth.id
    const { location } = req.body;
    await mysql(' insert into location (location,userid) values (?,?)',
        [location, userid]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//删除用户收货地址*************************************************************************************************
router.delete('/deleteLocation', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM location WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//修改用户收货地址*************************************************************************************************
router.put("/updateLocation", async function (req, res) {
    const { id, location } = req.body
    let cmd_filed = [];
    let cmd_arr = [];

    if (location) {
        cmd_filed.push("location=?")
        cmd_arr.push(location)
    }
    cmd_arr.push(Number(id))
    let sql = '';
    sql = " UPDATE location SET ";
    sql += cmd_filed.join(",");
    sql += " where id = ? "

    const usersql = await mysql(sql, cmd_arr)

    console.log(usersql);
    res.json({
        code: 200,
        flag: true,
        msg: '修改成功'
    })
})
//查询所有商品*************************************************************************************************
router.post('/getAllGoods', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM goods LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM goods '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//删除商品*************************************************************************************************
router.delete('/deleteGoods', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM goods WHERE id = ? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//修改商品*************************************************************************************************
router.put("/updateGoods", async function (req, res) {
    const { id, type, name, detail, hot, price, state } = req.body
    let cmd_filed = [];
    let cmd_arr = [];
    if (type) {
        cmd_filed.push("type=?")
        cmd_arr.push(type)
    }
    if (name) {
        cmd_filed.push("name=?")
        cmd_arr.push(name)
    }
    if (price) {
        cmd_filed.push("price=?")
        cmd_arr.push(price)
    }
    if (hot) {
        cmd_filed.push("hot=?")
        cmd_arr.push(hot)
    }
    if (state) {
        cmd_filed.push("state=?")
        cmd_arr.push(state)
    }
    if (detail) {
        cmd_filed.push("detail=?")
        cmd_arr.push(detail)
    }
    cmd_arr.push(Number(id))
    let sql = '';
    sql = " UPDATE goods SET ";
    sql += cmd_filed.join(",");
    sql += " ,updatedAt = now() where id = ? "

    const usersql = await mysql(sql, cmd_arr)

    console.log(usersql);
    res.json({
        code: 200,
        flag: true,
        msg: '修改成功'
    })
})
//增加商品*************************************************************************************************
router.post('/addGoods', async function (req, res) {
    const { type, name, detail, hot, price, state } = req.body;
    await mysql(' insert into goods (type, name, detail, hot, price, state,createdAt,updatedAt) values (?,?,?,?,?,?,now(),now())',
        [type, name, detail, hot, price, state]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//查询所有服务商品dui*************************************************************************************************
router.post('/getAllServegoods', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM servegoods LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM servegoods '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//删除服务商品*************************************************************************************************
router.delete('/deleteServegoods', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM servegoods WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//修改服务商品*************************************************************************************************
router.put("/updateServegoods", async function (req, res) {
    const { id, serveclassid, type, name, detail } = req.body
    let cmd_filed = [];
    let cmd_arr = [];
    if (type) {
        cmd_filed.push("type=?")
        cmd_arr.push(type)
    }
    if (name) {
        cmd_filed.push("name=?")
        cmd_arr.push(name)
    }
    if (serveclassid) {
        cmd_filed.push("serveclassid=?")
        cmd_arr.push(serveclassid)
    }
    if (detail) {
        cmd_filed.push("detail=?")
        cmd_arr.push(detail)
    }
    cmd_arr.push(Number(id))
    let sql = '';
    sql = " UPDATE servegoods SET ";
    sql += cmd_filed.join(",");
    sql += " ,updatedAt = now() where id = ? "

    const usersql = await mysql(sql, cmd_arr)

    console.log(usersql);
    res.json({
        code: 200,
        flag: true,
        msg: '修改成功'
    })
})
//增加服务商品*************************************************************************************************
router.post('/addGoods', async function (req, res) {
    const { serveclassid, type, name, detail } = req.body;
    await mysql(' insert into servegoods (serveclassid,type, name, detail,createdAt,updatedAt) values (?,?,?,?,now(),now())',
        [serveclassid, type, name, detail]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//添加帖子收藏*************************************************************************************************
router.post('/addSharefav', async function (req, res) {
    const { shareid, userid, name } = req.body;
    await mysql(' insert into sharefav (shareid, userid, name) values (?,?,?)',
        [shareid, userid, name]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//查询个人帖子收藏(根据id搜索)*************************************************************************************************
router.post('/getAllSharefavByid', async function (req, res) {
    const userid = req.auth.id
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM sharefav where userid = ? LIMIT ?,?',
        [userid, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM sharefav '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//查询帖子收藏*************************************************************************************************
router.post('/getAllSharefav', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM sharefav LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM sharefav '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//删除帖子收藏*************************************************************************************************
router.delete('/deleteSharefav', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM sharefav WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})
//添加商品收藏*************************************************************************************************
router.post('/addGoodfav', async function (req, res) {
    const { goodid, userid, name } = req.body;
    await mysql(' insert into goodfav (goodid, userid, name) values (?,?,?)',
        [goodid, userid, name]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//查询个人帖子收藏(根据id搜索)*************************************************************************************************
router.post('/getAllGoodfavByid', async function (req, res) {
    const userid = req.auth.id
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM goodfav where userid = ? LIMIT ?,?',
        [userid, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM goodfav '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//查询帖子收藏*************************************************************************************************
router.post('/getAllGoodfav', async function (req, res) {
    let { pageSize, currentPage } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 6;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM goodfav LIMIT ?,?',
        [(currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: total }] = await mysql(
        'SELECT count(*) as a FROM goodfav '
    )
    res.json({
        flag: true,
        code: 200,
        data,
        total,
    })
})
//删除帖子收藏*************************************************************************************************
router.delete('/deleteGoodfav', async function (req, res) {
    const { id } = req.query
    await mysql('DELETE FROM goodfav WHERE id=? ', [Number(id)])
    res.json({
        code: 200,
        flag: true,
        msg: '删除成功'

    })
})




//添加服务订单白倩**********************************************************************************************************
router.post('/addServeOrder', async function (req, res) {
    const { servegoodsname, classid, price, serveid, actiontime, endtime, userid } = req.body;
    await mysql(' insert into serveorder (servegoodsname,classid,price,serveid,createdAt,updatedAt,isconment,isok,actiontime,endtime,userid,receive) values (?,?,?,?,now(),now(),?,?,?,?,?,?)',
        [servegoodsname, classid, price, serveid, 0, 0, actiontime, endtime, userid, 0]);
    res.json({
        flag: true,
        code: 200,
        msg: '添加成功'
    })
})
//添加商品订单白倩*********************************************************************************************************
router.post('/addGoodsOrder', async function (req, res) {
    const { userid, goodid, name, price } = req.body;
    const result = await mysql('insert into `order` (userid, goodid,name,price,state,iscomment,createdAt,updatedAt) values (?,?,?,?,?,?,now(),now())',
        [userid, goodid, name, price, 0, 0]);
    if (result) {
        //增加商品销量
        const data = await mysql(
            'SELECT * FROM goods where id = ? ', [goodid]
        )
        await mysql("update goods set sale = ? where id = ? ", [Number(data[0].sale) + 1, goodid])
        res.json({
            flag: true,
            code: 200,
            msg: '添加成功',
        })
    } else {
        res.json({
            flag: true,
            code: 400,
            msg: '添加失败',

        })
    }


})



// ----------------------------------------------------------------bai------------------------------------------------------------------------------------


/**
 * 通过auth值获取对应用户
 * @api {post} api/getUsers 通过auth值获取对应用户
 * @apiName getUsers
 * @apiDescription 通过auth值获取对应用户
 * @apiGroup api
 * @apiVersion 1.0.0
 * @apiParam {number} pageSize 每页显示数
 * @apiParam {number} currentPage 当前页
 * @apiParam {number} auth 0超管1管理员2用户3服务员
 * @apiParamExample  {type} Request-Example:
 *    {
 *      "pageSize": 10,
 *      "currentPage": 1,
 *      "auth": 2
 *    }
 * @apiSuccessExample {type} Success-Response
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 0,
 *      "data": [],
 * "recordCount":10,
 *      "msg": "返回成功"
 *    }
 * @apiSampleRequest http://localhost:3000/api/getUsers
 * @apiUse CODE_200
 */
//查询用户
router.post('/getUsers', async function (req, res) {
    let { pageSize, currentPage, auth } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 10;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }

    const data = await mysql(
        'SELECT * FROM users where auth = ?  ORDER BY createdAt DESC LIMIT ?,?',
        [auth, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: recordCount }] = await mysql(
        'SELECT count(*) as a FROM users where auth=? ', [auth]
    )
    res.json({
        code: 200,
        data,
        recordCount,
        msg: '查询成功'
    })
})


/**
 * 通过id值获取用户详情
 * @api {get} api/getOneInfo 通过id值获取用户详情
 * @apiName getOneInfo
 * @apiDescription 通过id值获取用户详情
 * @apiGroup api
 * @apiVersion 1.0.0
 * @apiParam {number} id 用户id
 * @apiParamExample  {type} Request-Example:
 *    {
 *      "id": 2
 *    }
 * @apiSuccessExample {type} Success-Response
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 0,
 *      "data": {},
 * "info":{},
 *      "msg": "成功"
 *    }
 * @apiSampleRequest http://localhost:3000/api/getOneInfo
 * @apiUse CODE_200
 */

//用户详情
router.get('/getOneInfo', async function (req, res) {
    let { id } = req.query
    let info = ''
    let data = await mysql(
        'SELECT * FROM users where id = ? ',
        [id]
    )
    console.log(data[0].auth);
    if (data[0].auth == 3) {
        console.log('2222');
        info = await mysql(
            'SELECT * FROM servedetail where serveid = ? ',
            [id]
        )
        res.json({
            code: 200,
            data,
            info,
            msg: '获取用户信息成功'
        })
    } else {
        res.json({
            code: 200,
            data,
            msg: '获取用户信息成功'
        })
    }

})

/**
 * 通过id值删除用户
 * @api {get} api/deleteUser 通过id值删除用户
 * @apiName deleteUser
 * @apiDescription 通过id值删除用户
 * @apiGroup api
 * @apiVersion 1.0.0
 * @apiParam {number} id 用户id
 * @apiParamExample  {type} Request-Example:
 *    {
 *      "id": 2
 *    }
 * @apiSuccessExample {type} Success-Response
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 0,
 *      "msg": "成功"
 *    }
 * @apiSampleRequest http://localhost:3000/api/deleteUser
 * @apiUse CODE_200
 */

//删除某个用户
router.get('/deleteUser', async function (req, res) {
    let { id } = req.query
    await mysql('delete from users WHERE id=?', [id])
    res.json({
        code: 200,
        msg: '删除成功'
    })
})

//查询订单  type 1 服务订单 2商品订单 id没有为全部订单 有为单一用户订单
router.post('/getOrder', async function (req, res) {
    let { pageSize, currentPage, type, id } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 10;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    let biao = 'serveorder'

    if (type == 1) {
        biao = 'serveorder'
    } else {
        biao = 'order'
    }
    if (id) {
        const data = await mysql(
            `SELECT * from ${biao} where userid = ? ORDER BY createdAt DESC LIMIT ?,?`,
            [id, (currentPage - 1) * pageSize, pageSize]
        )

        const [{ a: recordCount }] = await mysql(
            `SELECT count(*) as a FROM ${biao} where userid=? `, [id]
        )
        res.json({
            code: 200,
            data,
            recordCount,
        })
    } else {
        console.log('55555');
        const data = await mysql(
            `SELECT * from ${biao} ORDER BY createdAt DESC LIMIT ?,?`,
            [(currentPage - 1) * pageSize, pageSize]
        )

        const [{ a: recordCount }] = await mysql(
            `SELECT count(*) as a FROM ${biao}  `
        )
        res.json({
            code: 200,
            data,
            recordCount,
        })
    }

})

//删除某个订单
router.get('/deleteUser', async function (req, res) {
    let { type, id } = req.query;
    let biao = 'serveorder'
    if (type == 1) {
        biao = 'serveorder'
    } else {
        biao = 'order'
    }
    await mysql(`delete from ${biao} WHERE id=?`, [id])
    res.json({
        code: 200,
        msg: '删除成功'
    })
})

//更改接单状态
router.post('/updateReceive', async function (req, res) {
    let { receive, id } = req.body
    await mysql('update serveorder set receive=? where id = ?', [receive, id])
    res.json({
        code: 200,
        msg: '接单成功'
    })
})

//更改订单是否完成状态
router.post('/updateIsok', async function (req, res) {
    let { isok, id } = req.body
    await mysql('update serveorder set isok=? where id = ?', [isok, id])
    res.json({
        code: 200,
        msg: '订单已完成'
    })
})

// //服务评价
// router.post('/updateIsconment', async function (req, res) {
//     let { isconment, id, content } = req.body
//     await mysql('update serveorder set isconment=? where id = ?', [isconment, id])
//     res.json({
//         code: 200,
//         msg: '订单已完成'
//     })
// })

//轮播图
router.get('/swiper', async function (req, res) {
    const data = await mysql('select * from swiper')
    res.json({
        code: 200,
        data,
        msg: '获取轮播图成功'
    })
})
// 根据employeetype查询员工 
router.post('/getServes', async function (req, res) {
    let { pageSize, currentPage, employeetype } = req.body;
    pageSize = Number(pageSize);
    if (Number.isNaN(pageSize)) {
        pageSize = 10;
    }
    currentPage = Number(currentPage);
    if (Number.isNaN(currentPage)) {
        currentPage = 1;
    }
    const data = await mysql(
        'SELECT * FROM users where employeetype = ?  ORDER BY createdAt DESC LIMIT ?,?',
        [employeetype, (currentPage - 1) * pageSize, pageSize]
    )

    const [{ a: recordCount }] = await mysql(
        'SELECT count(*) as a FROM users where employeetype=? ', [employeetype]
    )
    res.json({
        code: 200,
        data,
        recordCount,
        msg: '查询成功'
    })
})

//查询省
router.get('/province', async function (req, res) {
    const data = await mysql('select * from tb_province')
    res.json({
        code: 200,
        data,
        msg: '获取省成功'
    })
})
//查询市
router.get('/city', async function (req, res) {
    let { province_id } = req.query
    const data = await mysql('select * from tb_city where province_id = ?', [province_id])

    res.json({
        code: 200,
        data,
        msg: '获取市成功'
    })
})
//查询区
router.get('/town', async function (req, res) {
    let { city_id } = req.query
    const data = await mysql('select * from tb_town where city_id = ?', [city_id])
    res.json({
        code: 200,
        data,
        msg: '获取区成功'
    })
})

// ----------------------------------------------------------------bai------------------------------------------------------------------------------------









module.exports = router;
